package com.ruoyi.common.utils;


import java.lang.reflect.Method;
import java.util.*;

public class MapUtil {

    public static Map json2Map(String jsonStr) {
        return JSONUtils.fromJson(jsonStr, Map.class);
    }


    /**
     * @param list
     * @param field
     * @return
     * @Description 将list转换为map
     * @author zhangxh
     * @date 2016-8-11 下午9:28:05
     * @lastModifier
     */
    public static <T, T2> Map<T2, T> toMap(List<T> list, String field, Class<T2> cla) {
        Map<T2, T> result = new HashMap<T2, T>();
        if (list == null || list.isEmpty()) {
            return result;
        }
        String methodName = "get" + (field.charAt(0) + "").toUpperCase() + field.substring(1);
        for (T o : list) {
            if (o == null) continue;
            Class<?> clazz = o.getClass();
            try {
                Method method = clazz.getMethod(methodName);
                Object value = method.invoke(o);
                Method valueOf = cla.getMethod("valueOf", String.class);
                if (value == null) {
                    result.put((T2) valueOf.invoke(null, "0"), o);
                } else {
                    result.put((T2) valueOf.invoke(null, value.toString()), o);
                }

            } catch (Exception e) {

            }
        }
        return result;
    }


    /**
     * @param list
     * @param field
     * @return
     * @Description 将list转换为map
     * @author zhangxh
     * @date 2016-8-11 下午9:28:05
     * @lastModifier
     */
    public static <T> Map<Long, T> toMap(List<T> list, String field) {
        return toMap(list, field, Long.class);
    }

    /**
     * 使用 Map按key进行排序
     *
     * @param map
     * @return
     */
    public static Map<String, Object> sortMapByKey(Map<String, Object> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }
        Map<String, Object> sortMap = new TreeMap<String, Object>(
                new Comparator<String>() {
                    @Override
                    public int compare(String str1, String str2) {
                        return str1.compareTo(str2);
                    }
                });

        sortMap.putAll(map);

        return sortMap;
    }

}
